<style lang="scss" type="text/scss">
  @import "../../assets/chartEdit.scss";
</style>
<template>
  <div>
    <div class="page-main-body">
      <div class="page-main-left" :style="'width:'+leftWidth+'px'">
        <el-menu :default-active="pathUrl" mode="horizontal" :router="true">
          <el-menu-item :index="pathUrl">图表项</el-menu-item>
          <el-menu-item :index="pathUrl+'/ds'">数据源
          </el-menu-item>
        </el-menu>
        <div class="line"></div>
        <div class="left-menu" v-loading="isLoading">
          <h3>维度
            <a href="javascript:">
              <i class="el-icon-plus"></i>
            </a>
          </h3>
          <draggable v-model="chartSeries.category" :options="dragOp.f"
                     @add="checkDistinctSeries('category')" :move="checkTagSeriesMove">
            <transition-group tag="ul" class="menu-series">
              <li v-for="item in chartSeries.category" :key="item.name">
                <span>{{item.title}}</span>
                <el-dropdown @command="mdOpera">
                  <span class="el-dropdown-link">
                   <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{operate:'rename',item:item}">修改名称</el-dropdown-item>
                    <el-dropdown-item :command="{operate:'m',item:item}">转化为维度</el-dropdown-item>

                  </el-dropdown-menu>
                </el-dropdown>
              </li>
            </transition-group>
          </draggable>
          <h3>度量
            <a href="javascript:">
              <i class="el-icon-plus"></i>
            </a>
          </h3>
          <draggable v-model="chartSeries.value" :options="dragOp.f"
                     @add="checkDistinctSeries('value')" :move="checkTagSeriesMove">
            <transition-group tag="ul" class="menu-series">
              <li v-for="item in chartSeries.value" :key="item.name">
                <span>{{item.title}}</span>
                <el-dropdown @command="mdOpera">
                  <span class="el-dropdown-link">
                   <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{operate:'rename',item:item}">修改名称</el-dropdown-item>
                    <el-dropdown-item :command="{operate:'d',item:item}">转化为维度</el-dropdown-item>
                    <el-dropdown-item :command="{operate:'cm',item:item}">更换计算方法</el-dropdown-item>

                  </el-dropdown-menu>
                </el-dropdown>
              </li>
            </transition-group>
          </draggable>
        </div>
      </div>
      <div class="page-main-left2">
        <el-card>
          <h4>筛选器</h4>

          <draggable v-model="chartTag.filters" :options="dragOp.f"
                     @add="changeItemMul(chartTag.filters,'filters')"
                     style="min-height:200px;" class="tag-tip-list">
            <el-tag size="small" type="success" :disable-transitions="true" v-if="chartTag.filters.length>0"
                    v-for="tag in chartTag.filters" :key="tag.name" closable @close="axisClose(tag,'filters')">
              {{tag.title}}
              <span class="pull-right">过滤 </span>
            </el-tag>
          </draggable>
        </el-card>
        <el-card>
          <h4>标记</h4>
          <!-- <el-select value="" size="mini" class="w-100">
             <el-option value="0">自动</el-option>
             <el-option value="1">圆</el-option>
           </el-select>-->
          <div class="chart-tag-list">
            <el-tag key="color">
              <draggable class="tag-axis" v-model="chartTag.color" :options="dragOp.t"
                         @add="changeItemOne(chartTag.color,'color')">
                颜色
              </draggable>
            </el-tag>
            <!-- <el-tag>
               <draggable class="tag-axis" v-model="chartTag.size" :options="dragOp.t" @add="changeItemOne(chartTag.size,'size')">
                 大小
               </draggable>
             </el-tag>-->
            <el-tag>
              <draggable class="tag-axis" v-model="chartTag.tag" :options="dragOp.t"
                         @add="changeItemMul(chartTag.tag,'tag')">
                标签
              </draggable>
            </el-tag>
            <el-tag>
              <draggable class="tag-axis" v-model="chartTag.detail" :options="dragOp.t"
                         @add="changeItemMul(chartTag.detail,'detail')">
                详细信息
              </draggable>
            </el-tag>
            <el-tag>
              <draggable class="tag-axis" v-model="chartTag.tip" :options="dragOp.t"
                         @add="changeItemMul(chartTag.tip,'tip')">
                工具提示
              </draggable>
            </el-tag>
          </div>
          <div class="tag-tip-list">
            <el-tag size="small" type="success" :disable-transitions="true" v-if="chartTag.color.length>0"
                    v-for="tag in chartTag.color" :key="'color_'+tag.name" closable @close="axisClose(tag,'color')">
              颜色
              <span class="pull-right">{{tag.title}} </span>
            </el-tag>
            <el-tag size="small" type="success" :disable-transitions="true" v-if="chartTag.size.length>0"
                    v-for="tag in chartTag.size" :key="'size_'+tag.name" closable @close="axisClose(tag,'size')">
              大小
              <span class="pull-right">{{tag.title}} </span>
            </el-tag>
            <el-tag size="small" type="success" :disable-transitions="true" v-if="chartTag.tag.length>0"
                    v-for="tag in chartTag.tag" :key="'tag_'+tag.name" closable @close="axisClose(tag,'tag')">
              标签
              <span class="pull-right">{{tag.title}}</span>
            </el-tag>
            <el-tag size="small" type="success" :disable-transitions="true" v-if="chartTag.detail.length>0"
                    v-for="tag in chartTag.detail" :key="'detail_'+tag.name" closable @close="axisClose(tag,'detail')">
              详细信息
              <span class="pull-right">{{tag.title}} </span>
            </el-tag>
            <el-tag plain size="small" type="success" :disable-transitions="true" v-if="chartTag.tip.length>0"
                    v-for="tag in chartTag.tip" :key="'tip_'+tag.name" closable @close="axisClose(tag,'tip')">
              工具提示
              <span class="pull-right">{{tag.title}}</span>
            </el-tag>
          </div>
        </el-card>

      </div>
      <div class="page-main-right" :style="'width:'+rightWidth" v-loading="isLoading">
        <div class="chart-tag-axis">
          <div>
            <label>行</label>
            <draggable class="axis-list" v-model="chartTag.xAxis" :options="dragOp.t"
                       @add="changeItemMul(chartTag.xAxis,'xAxis')" :move="checkSeriesMove">

              <el-tag v-for="item in chartTag.xAxis" size="small" :key="item.name" closable
                      @close="axisClose(item,'xAxis')">
                {{item.title}}
              </el-tag>
            </draggable>
          </div>
          <div>
            <label>列</label>
            <draggable class="axis-list" v-model="chartTag.yAxis" :options="dragOp.t"
                       @add="changeItemMul(chartTag.yAxis,'yAxis')" :move="checkSeriesMove">

              <el-tag v-for="item in chartTag.yAxis" size="small" :key="item.name" closable
                      @close="axisClose(item,'yAxis')">
                {{item.title}}
              </el-tag>
            </draggable>
          </div>
        </div>

        <transition name="scale" mode="out-in" appear>
          <router-view class="chart-body" v-if="hasDataset"></router-view>
        </transition>
      </div>
    </div>
    <d-tom-dialog :show="showFieldD2M" :field="fieldD2M" @close="changeD2M"></d-tom-dialog>
  </div>
</template>

<script>
  import {http, chart, measure, dimension} from '../../resources';
  import utils from '@/tools/utils';
  import opera from '@/action/opera';
  import DTomDialog from '../../action/dTomDialog.vue';

  export default {

    components: {DTomDialog},
    data: function () {
      return {
        fieldD2M: {},
        showFieldD2M: false,
        isLoading: true,
        chartInfo: {}, // 当前表信息
        leftWidth: 240, // 左侧宽度
        chartSeries: { // 图表项
          category: [],
          value: []
        },
        chartList: [],
        dragOp: {
          f: {
            group: {
              name: 'axis',
              pull: 'clone'
              // put: false
            },
            ghostClass: 'ghost'
          },
          t: {
            group: {
              name: 'axis'
              // pull: false
            },
            // draggable: '.item',
            disabled: false,
            ghostClass: 'ghost'
          }

        },
        chartTag: { // 图片操作存放信息
          color: [],
          size: [],
          detail: [],
          tag: [],
          tip: [],
          xAxis: [],
          yAxis: [],
          filters: []
        },
        timer: {
          chartOpt: '',
          chartData: ''
        }, // 时间参数去重用s,
        isSeriesChange: false
      };
    },
    computed: {
      rightWidth: function () {
        let width = this.$store.state.bodyWidth - this.leftWidth;

        width = width - 260;

        return width + 'px';
      },
      hasDataset: function () {
        return this.chartInfo.datasetId;
      },
      pathUrl: function () {
        return `/project/${this.$route.params.projectId}/chart/${this.$route.params.chartId}`;
      },
      chartId: function () {
        return this.$route.params.chartId;
      }
    },
    watch: {
      chartTag: {
        handler(form) {
          this.changeChartOpt();
        },
        deep: true
      }
    },
    mounted() {
      this.getChartInfo();
    },
    methods: {
      changeD2M() {
        this.showFieldD2M = false;
        this.getSeries();
      },
      chartTagValid(tag) {
        if (tag === null || typeof tag !== 'object') return [];
        let series = [].concat(this.chartSeries.category, this.chartSeries.value);
        Object.keys(tag).forEach(key => {
          let fields = [];
          let fieldList = tag[key];
          fieldList.forEach(field => {
            for (let currentSeries of series) {
              if (currentSeries.id === field.id) {
                fields.push(currentSeries);
                break;
              }
            }
          });
          tag[key] = fields;
        });
        return tag;
      },
      getChartInfo: function () {
        chart.get(this.$route.params.chartId).then(res => {
          if (!res || !res.data || !res.data.datasetId) {
            this.$router.replace({
              path: `/project/${this.$route.params.projectId}/chart/${this.$route.params.chartId}/ds`
            });
            return false;
          }
          this.chartInfo = res.data;
          this.getSeries().then(valid => {
            if (this.chartInfo.tag && utils.isString(this.chartInfo.tag)) {
              this.chartInfo.tag = this.chartTagValid(JSON.parse(this.chartInfo.tag));
            }
            if (this.chartInfo.opt && utils.isString(this.chartInfo.opt)) {
              this.chartInfo.opt = JSON.parse(this.chartInfo.opt);
            }
            if (this.chartInfo.tag) {
              this.chartTag = Object.assign(this.chartTag, this.chartInfo.tag);
            }
          });
        });
      },
      getSeries() {
        return new window.Promise((resolve, reject) => {
          let url = '/series/' + this.chartInfo.datasetId;
          http.get(url).then(RES => {
            let series = RES.data.data;
            let categoryArr = [];
            let valueArr = [];
            series.forEach(item => {
              if (item.id) {
                item.name = item.id;
              }
              if (item.type === 'category') {
                categoryArr.push(item);
              } else {
                valueArr.push(item);
              }
            });
            sessionStorage.setItem(
              'ds_' + this.chartInfo.chartId + '_series',
              JSON.stringify(series)
            );
            this.chartSeries.category = categoryArr;
            this.chartSeries.value = valueArr;
            this.isLoading = false;
            this.changeChartOpt();
            resolve(true);
          });
        });

      },
      checkSeriesScoped(arr) {
        let tempArr = [];
        let scopeArr = [].concat(this.chartTag.xAxis, this.chartTag.yAxis, this.chartSeries.value);
        let isIn = false;
        arr.forEach(item => {
          isIn = false;
          scopeArr.forEach(item2 => {
            if (item2.name === item.name) {
              isIn = true;
            }
          });
          if (isIn) {
            tempArr.push(item);
          }
        });
        return tempArr;
      },
      changeItemOne(item, type) {
        let arr = item.filter((r, index) => {
          return index === 0;
        });
        if (arr.length > 0) {
          this.chartTag[type] = arr;
        }
      },
      changeItemMul: function (currentArr, type) {
        let arr = [];
        let isIn = false;
        currentArr.forEach(item => {
          isIn = false;
          arr.forEach(v => {
            if (v.name === item.name) {
              isIn = true;
            }
          });
          if (!isIn) {
            arr.push(item);
          }
        });
        this.chartTag[type] = arr;
      },
      startDrop(a, b) {
      },
      axisClose(item, type) {
        this.chartTag[type] = this.chartTag[type].filter(element => {
          return element !== item;
        });
      },
      changeChartOpt() {
        clearTimeout(this.timer.chartOpt);
        this.timer.chartOpt = setTimeout(() => {
          this.$store.commit('chartOptionChange', false);
          sessionStorage.setItem(
            'charts_' + this.chartInfo.chartId + '_chartTag',
            JSON.stringify(this.chartTag)
          );
          this.$store.commit('chartOptionChange', true);
        }, 500);

      },
      checkDistinctSeries(type = '') {
        let chartSeries = [].concat(this.chartSeries.value, this.chartSeries.category);
        let arr = [];
        let cArr = [];
        let vArr = [];
        let isIn = false;
        let type1 = 'category';
        let type2 = 'value';

        if (type === 'value') {
          type2 = 'category';
          type1 = 'value';
        }
        this.chartSeries[type1].forEach(item => {
          isIn = false;
          arr.forEach(v => {
            if (v.name === item.name) {
              isIn = true;
            }
          });
          if (!isIn) {
            arr.push(item);
            cArr.push(item);
          }
        });
        this.chartSeries[type1] = cArr;

        this.chartSeries[type2].forEach(item => {
          isIn = false;
          arr.forEach(v => {
            if (v.name === item.name) {
              isIn = true;
            }
          });
          if (!isIn) {
            arr.push(item);
            vArr.push(item);
          }
        });
        this.chartSeries[type2] = vArr;
      },
      checkSeriesMove(evt) {
        if (evt.to.className !== 'axis-list') {
          return false;
        }
      },
      checkTagSeriesMove(evt) {
        this.isSeriesChange = evt.to.className === 'menu-series';
        if (evt.to.className === 'tag-axis') {
          let arr = [].concat(this.chartTag.xAxis, this.chartTag.yAxis, this.chartSeries.value);
          for (let item of arr) {
            if (item.name === evt.draggedContext.element.name) {
              return true;
            }
          }
          return false;
        }
      },
      mdOpera(commandObj) {
        let currentFeild = commandObj.item;
        let sType = currentFeild.id.substr(0, 1);
        let modal;
        if (sType === 'd') {
          modal = dimension;
        } else {
          modal = measure;
        }
        switch (commandObj.operate) {
          case 'rename':
            opera.rename(modal, currentFeild.id, currentFeild.title).then(res => {
              this.getChartInfo();
            });
            break;
          case 'hidden':
            opera.delete(modal, currentFeild.id).then(res => {
              this.getChartInfo();
            });
            break;
          case 'm':
          case 'cm':
            this.fieldD2M = currentFeild;
            this.showFieldD2M = true;
            break;
          case 'd':
            opera.dTom(currentFeild, this).then(res => {
              this.getChartInfo();
            });

            break;
          default:
            break;
        }
      }
    }
  };
</script>
